package colin.project.sso.server.config;

import cn.hutool.db.ds.druid.DruidDSFactory;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author joker
 * @Title DataSourceConfig
 * @Description
 * @Date 2019/5/17 9:23 PM
 * @Since
 * @Version 1.0.0
 */
@Configuration
public class DataSourceConfig {

    @Value(value = "${jdbc.url}")
    private String jdbcURL;

    @Value(value = "${jdbc.username}")
    private String jdbcUsername;

    @Value(value = "${jdbc.password}")
    private String jdbcPassword;

    private Environment environment;

    @Bean(name = "datasource")
    public DataSource master() throws Exception {
        return DruidDataSourceFactory.createDataSource(dataSourceProps());
    }

    private Map<String, Object> dataSourceProps() {
        Map<String, Object> configs = new HashMap<>();
        configs.put("url", jdbcURL);
        configs.put("username", jdbcUsername);
        configs.put("password", jdbcPassword);
        configs.put("filters", "stat");
        configs.put("maxActive", "20");
        configs.put("initialSize", "1");
        configs.put("maxWait", "60000");
        configs.put("minIdle", "1");
        configs.put("timeBetweenEvictionRunsMillis", "60000");
        configs.put("minEvictableIdleTimeMillis", "300000");
        configs.put("testWhileIdle", "true");
        configs.put("testOnBorrow", "false");
        configs.put("testOnReturn", "false");
        configs.put("poolPreparedStatements", "true");
        configs.put("maxOpenPreparedStatements", "20");
        configs.put("asyncInit", "true");
        return configs;
    }

    // 其中 dataSource 框架会自动为我们注入
    @Bean
    public PlatformTransactionManager txManager() throws Exception {
        return new DataSourceTransactionManager(master());
    }
}
